var history_query = function() {
	return {
		/**
		 * 页面初始化方法
		 */
		init:function(pCode){
			//初始化下电池下拉框
			$("#query_pack_code").select2({
				language: "zh-CN",
				allowClear: true,
				width: "175px",
				placeholder: "请选择",
				ajax: {
					url: "monitor/historyQuery/getPackCodeOptions2.mvc",
					dataType: 'json',
					delay: 250,
					data: function (params) {
						params.offset = 10;
						params.page = params.page || 1;
						return {
							name: params.term||(pCode == 'null'?params.term:pCode),
							page: params.page,
							offset: params.offset
						};
					},
					cache: false,
					processResults: function (res, params) {
							var users = res.data;
							var options = [];
							for (var i = 0, len = users.length; i < len; i++) {
								var option = {
									"id": users[i]["serialNo"],
									"text": (users[i]["serialNo"])
								};
								options.push(option);
							}
							return {
								results: options,
								pagination: {
									more: (params.page * params.offset) < res.total
								}
							};
					},
					escapeMarkup: function (markup) {
						return markup;
					},
					minimumInputLength: 1
				}
			});
			if(pCode != 'null'){
				$('#query_pack_code').html('<option value="'+pCode+'">'+pCode+'</option>').trigger("change")
			}
			//初始加载表格
			history_query.setDefaultChart();
			//重置按钮事件
			$("#btn_reset").click(function(){
				$("#history_query_form")[0].reset();
			});
			
			$('.enterSearch').bind('keyup', function(event) {
					if (event.keyCode == "13") {
						//回车执行查询
						$('#btn_query').click();
					}
			});
			
			//查询按钮事件
			$("#btn_query").click(function(){
				
				//时间选择框范围限制
				if($("#query_startTime").val() && $("#query_endTime").val()){
					var date1 = new Date($("#query_startTime").val());
					var date2 = new Date($("#query_endTime").val());
					var s1 = date1.getTime(),s2 = date2.getTime();
					if(parseInt((s2 - s1)/1000 / (24*60*60)) > 7){
						rmsBox.notify('warning', {msg: '日期范围已超出一周！', delay:3000});
						return;
					}
				}
				if(!$("#query_type").val()){
					return false;
				}  else {
				 	$.ajax({
						"type" : "post",
						"url" : "monitor/historyQuery/getHistoryChartData.mvc",
						"async" : true,
						"data":{
							'packCode':$("#query_pack_code").val(),
							'startTime':$("#query_startTime").val(),
							'endTime':$("#query_endTime").val(),
							'type':$("#query_type").val()
						},
						"dataType":"json",
						"beforeSend":function(){
							console.log("执行前");
							App.blockUI($(".histtory_query_chart_div"));
						},
						"success" : function(res) {
							console.log(res);
							debugger;
							   var chart_datas = res;
							   if(chart_datas && chart_datas.length >0){
								   if($("#query_type").val()=='7'){
									   $("#histtory_query_chart_div").empty();
									   var ulHtml = "";
									   ulHtml = '<ul class = "bar-box" id = "minitor_pack_chart" style = "height:auto;"></ul>';
									   $("#histtory_query_chart_div").append(ulHtml);
									   //电压  先遍历 创建图表格数 再遍历 创建series格数
									   $.each(chart_datas, function(i, item){
										 //动态创建表格
											if(item.data.length>0) {
												var chartHtml = "";
												chartHtml += '<li> <div class="echarts-title"> ';
												chartHtml += '<span class = "c-bold">第'+item.volGroupNo+'组</span>';
												chartHtml += '</div>';
												chartHtml += '<div id="chart_'+i+'"class="echats"></div>';
												$("#minitor_pack_chart").append(chartHtml);
												var series = new Array();
												var legendData = new Array();
												$.each(item.data, function(k, single){
													var s = {
															name:single.coreNo,
												            type:'line',
												            data:single.yData,
												            markPoint: {
												                data: [
												                    {type: 'max', name: '最大值'},
												                    {type: 'min', name: '最小值'}
												                ]
												            }
													};
													series.push(s);
													legendData.push(single.coreNo);
												});
												history_query.chart_vol_config(legendData, item.data[i].xData, "V", series, "chart_" + i, "电压", "{b}<br/>{a} : {c}V");
											}
									   })
								   } else if ($("#query_type").val()=='6'){
									   $("#histtory_query_chart_div").empty();
									   var ulHtml = "";
									   ulHtml = '<ul class = "bar-box" id = "minitor_pack_chart" style = "height:auto;"></ul>';
									   $("#histtory_query_chart_div").append(ulHtml);
									   //电压  先遍历 创建图表格数 再遍历 创建series格数
									   $.each(chart_datas, function(i, item){
										 //动态创建表格
										    if(item.data.length>0) {
												var chartHtml = "";
												chartHtml += '<li> <div class="echarts-title"> ';
												chartHtml += '<span class = "c-bold">第'+item.volGroupNo+'组</span>';
												chartHtml += '</div>';
												chartHtml += '<div id="chart_'+i+'"class="echats"></div>';
												$("#minitor_pack_chart").append(chartHtml);
												var series = new Array();
												var legendData = new Array();
												$.each(item.data, function(k, single){
													var s = {
															name:single.coreNo,
												            type:'line',
												            data:single.yData,
												            markPoint: {
												                data: [
												                    {type: 'max', name: '最大值'},
												                    {type: 'min', name: '最小值'}
												                ]
												            }
													};
													series.push(s);
													legendData.push(single.coreNo);
												})
												
												history_query.chart_vol_config(legendData, item.data[i].xData, "℃", series, "chart_" + i, "温度", "{b}<br/>{a} : {c}℃")
											}
									   })
									   
								   } else {
									   
										var gatherTimeData = new Array();
										var socData = new Array();
										var totalVolData = new Array();
										var totalElData = new Array();
										var maxTempData = new Array();
										var minTempData = new Array();
										var tempDiffData = new Array();
										var maxVolData = new Array();
										var minVolData = new Array();
										var volDiffData = new Array();
										if(chart_datas.length >0){
											 $("#histtory_query_chart_div").remove();
											 
											 var html = "";
											 html = '<div id="histtory_query_chart_div" style="width:100%;height:400px"></div>';
											 $("#test").append(html);
											for (var index = 0; index < chart_datas.length; index++) {
												gatherTimeData.push(chart_datas[index] ['gatherTime']);
												socData.push(chart_datas[index] ['soc']);
												totalVolData.push(chart_datas[index] ['totalVol']);
												totalElData.push(chart_datas[index] ['totalCurrent']);
												maxTempData.push(chart_datas[index] ['maxTemp']);
												minTempData.push(chart_datas[index] ['minTemp']);
												tempDiffData.push(chart_datas[index] ['tempDiff']);
												maxVolData.push(chart_datas[index] ['maxVol']);
												minVolData.push(chart_datas[index] ['minVol']);
												volDiffData.push(chart_datas[index] ['volDiff']);
										    }
										} 
								   }
							   } else {
									//没有数据
									rmsBox.notify('warning', {msg: '无数据！', delay:1000});
							   }
								switch($("#query_type").val()){
										case '0':
										//soc
										var series = [
								        {
								            name:'soc',
								            type:'line',
								            data:socData,
								            markPoint: {
								                data: [
								                    {type: 'max', name: '最大值'},
								                    {type: 'min', name: '最小值'}
								                ]
								            }
								        }
								    ]
										history_query.chart_config("SOC曲线图",['SOC'], gatherTimeData, '%', series, "histtory_query_chart_div", 'SOC', "{b}<br/>{a} : {c}%");
										
									break;
										case '1':
										//总电压
									  var series = [
								        {
								            name:'总电压',
								            type:'line',
								            data:totalVolData,
								            markPoint: {
								                data: [
								                    {type: 'max', name: '最大值'},
								                    {type: 'min', name: '最小值'}
								                ]
								            }
								        }
								    ]
										history_query.chart_config("总电压曲线图",['总电压'], gatherTimeData, '', series, "histtory_query_chart_div", '总电压(V)',"{b}<br/>{a} : {c}V");
									
									break;
										case '2':
										//总电流
										var series = [
								        {
								            name:'总电流',
								            type:'line',
								            data:totalElData,
								            markPoint: {
								                data: [
								                    {type: 'max', name: '最大值'},
								                    {type: 'min', name: '最小值'}
								                ]
								            }
								        }
								    ]
										history_query.chart_config("总电流曲线图",['总电流'], gatherTimeData, '', series, "histtory_query_chart_div", '总电流(A)', "{b}<br/>{a} : {c}A");
									
									break;
										case '3':
										//监测点最高温度
										 var series = [
								        {
								            name:'监测点最高温度',
								            type:'bar',
								            data:maxTempData,
								            markPoint: {
								                data: [
								                    {type: 'max', name: '最大值'},
								                    {type: 'min', name: '最小值'}
								                ]
								            },
								            itemStyle: {
								            	normal: {
								            		color: '#FB824E'
								            	}
								            }
								        }
								    ]
										history_query.chart_config("监测点最高温度曲线图",['监测点最高温度'], gatherTimeData, '℃', series, "histtory_query_chart_div", '温度(℃)', "{b}<br/>{a} : {c}℃");
									
									break;
									    case '4':
									    //监测点温度与温差
									    var series = [
								        {
								            name:'监测点最高温度',
								            type:'line',
								            data:maxTempData,
								            markPoint: {
								                data: [
								                    {type: 'max', name: '最大值'},
								                    {type: 'min', name: '最小值'}
								                ]
								            }
								        },
								         {
								            name:'监测点最低温度',
								            type:'line',
								            data:minTempData,
								            markPoint: {
								                data: [
								                    {type: 'max', name: '最大值'},
								                    {type: 'min', name: '最小值'}
								                ]
								            }
								        },
								         {
								            name:'温差',
								            type:'line',
								            data:tempDiffData,
								            yAxisIndex: 1,
								            markPoint: {
								                data: [
								                    {type: 'max', name: '最大值'},
								                    {type: 'min', name: '最小值'}
								                ]
								            }
								        }
								    ]
										history_query.chart_config_twoY("监测点温度极值与温差曲线图",['监测点最高温度', '监测点最低温度', '温差'], gatherTimeData, '℃', series, "histtory_query_chart_div", '温度(℃)','温差(℃)', "{b}<br/>{a} : {c}℃");
									
									break;
										case '5':
										//单体电压与压差
										var series = [
								        {
								            name:'单体最高电压',
								            type:'line',
								            data:maxVolData,
								            markPoint: {
								                data: [
								                    {type: 'max', name: '最大值'},
								                    {type: 'min', name: '最小值'}
								                ]
								            }
								        },
								         {
								            name:'单体最低电压',
								            type:'line',
								            data:minVolData,
								            markPoint: {
								                data: [
								                    {type: 'max', name: '最大值'},
								                    {type: 'min', name: '最小值'}
								                ]
								            }
								        },
								         {
								            name:'压差',
								            type:'line',
								            data:volDiffData,
								            yAxisIndex: 1,
								            markPoint: {
								                data: [
								                    {type: 'max', name: '最大值'},
								                    {type: 'min', name: '最小值'}
								                ]
								            }
								        }
								    ]
										history_query.chart_config_twoY("单体电压极值与压差曲线图",['单体最高电压', '单体最低电压', '压差'], gatherTimeData, 'V', series, "histtory_query_chart_div", '电压(V)', '压差(V)',"{b}<br/>{a} : {c}V");
									
									break;
									default:
									console.log("无此选项");
								}
						},
						"error":function(){
							App.unblockUI($(".histtory_query_chart_div"));//停止loading
							rmsBox.notify('error', {msg: '查询出错了！', delay:3000});
						},
						"complete":function(){
							App.unblockUI($(".histtory_query_chart_div"));
						}
			        });
				}
			})
		},
		
		/**
		 * 配置echart
		 * @param title 图表标题
		 * @param legendData 系列
		 * @param dataX x轴数据
		 * @param unit y轴单位
		 * @param 系列数据
		 * @param chart_div_id 图表div_id
		 */
		chart_vol_config:function(legendData, dataX, unit, series, chart_div_id, yaxisName, tooltipFormat){
					option = {
					  /*  title: {
					        text: title
					    },*/
					    tooltip: {
					        trigger: 'axis'	,
					        formatter:tooltipFormat
					    },
					    legend: {
					        data:legendData
					    },
					    toolbox: {
					        show: true,
					        feature: {
					            dataZoom: {
					                yAxisIndex: 'none'
					            },
					            restore: {},
					            saveAsImage: {}
					         
							}
					    },
					    dataZoom : {
					        show : true,
					        realtime : true,
					        start : 0,
					        end : 100
					    },
					    xAxis:  {
					        type: 'category',
					        name:'时间',
					        splitLine:{show:true},
					        nameTextStyle:{
					        	color:'#89CBFD'
					        },
					        boundaryGap: false,
					        data: dataX
					    },
					    yAxis: {
					        type: 'value',
					        name:yaxisName,
					        splitLine:{show:true},
					        nameTextStyle:{
					        	color:'#89CBFD'
					        },
					        axisLabel: {
					            formatter: '{value}'+unit
					        }
					    },
					    series: series
					};
			    var myChart = echarts.init(document.getElementById(chart_div_id));
			    myChart.setOption(option, true);
			    App.unblockUI($("#histtory_query_chart_div"));//停止loading
		},
		
		/**
		 * 配置echart
		 * @param title 图表标题
		 * @param legendData 系列
		 * @param dataX x轴数据
		 * @param unit y轴单位
		 * @param 系列数据
		 * @param chart_div_id 图表div_id
		 */
		chart_config:function(title, legendData, dataX, unit, series, chart_div_id, yaxisName, tooltipFormat){
					option = {
					    title: {
					        text: title
					    },
					    tooltip: {
					        trigger: 'axis'	,
					        formatter:tooltipFormat
					    },
					    legend: {
					        data:legendData
					    },
					    toolbox: {
					        show: true,
					        feature: {
					        	myTool : {
					                show : true,
					                title : '下载历史数据表',
					                icon : 'image://./pages/history/css/image/file.png',
					                onclick : function(){
					                	if($("#query_startTime").val() && $("#query_endTime").val()){
											var date1 = new Date($("#query_startTime").val());
											var date2 = new Date($("#query_endTime").val());
											var s1 = date1.getTime(),s2 = date2.getTime();
											if(parseInt((s2 - s1)/1000 / (24*60*60)) > 31){
												rmsBox.notify('warning', {msg: '日期范围已超出一个月！', delay:3000});
												return;
											}
										}
										if(!$("#query_type").val()){
											return false;
										} else {
											App.blockUI($(".histtory_query_chart_div"));//开始loading
											var params = {};
											params.packCode = $("#query_pack_code").val();
											params.startTime = $("#query_startTime").val();
											params.endTime = $("#query_endTime").val();
											params.option = $("#query_type").val();
											util.ajaxDownload("monitor/historyQuery/export.mvc", params, ".histtory_query_chart_div");
					                }
					               }
					            },
					            dataZoom: {
					                yAxisIndex: 'none'
					            },
					            restore: {},
					            saveAsImage: {}
					         
							}
					    },
					    dataZoom : {
					        show : true,
					        realtime : true,
					        start : 0,
					        end : 100
					    },
					    xAxis:  {
					        type: 'category',
					        name:'时间',
					        splitLine:{show:true},
					        nameTextStyle:{
					        	color:'#89CBFD'
					        },
					        boundaryGap: false,
					        data: dataX
					    },
					    yAxis: {
					        type: 'value',
					        name:yaxisName,
					        splitLine:{show:true},
					        nameTextStyle:{
					        	color:'#89CBFD'
					        },
					        axisLabel: {
					            formatter: '{value}'+unit
					        }
					    },
					    series: series
					};
			    var myChart = echarts.init(document.getElementById(chart_div_id));
			    myChart.setOption(option,true);
			    App.unblockUI($("#histtory_query_chart_div"));//停止loading
		},
		
				/**
		 * 配置echart 双Y轴
		 * @param title 图表标题
		 * @param legendData 系列
		 * @param dataX x轴数据
		 * @param unit y轴单位
		 * @param tooltipFormat tooltip格式化
		 * @param 系列数据
		 * @param chart_div_id 图表div_id
		 */
		chart_config_twoY:function(title, legendData, dataX, unit, series, chart_div_id, yaxisName, yaxisName2, tooltipFormat){
					option = {
					    title: {
					        text: title
					    },
					    tooltip: {
					        trigger: 'axis'	,
					        formatter: tooltipFormat
					    },
					    legend: {
					        data:legendData
					    },
					    toolbox: {
					        show: true,
					        feature: {    	
					                myTool : {
					                show : true,
					                title : '下载历史数据表',
					                icon : 'image://./pages/history/css/image/file.png',
					                onclick : function(){
					                	if($("#query_startTime").val() && $("#query_endTime").val()){
											var date1 = new Date($("#query_startTime").val());
											var date2 = new Date($("#query_endTime").val());
											var s1 = date1.getTime(),s2 = date2.getTime();
											if(parseInt((s2 - s1)/1000 / (24*60*60)) > 31){
												rmsBox.notify('warning', {msg: '日期范围已超出一个月！', delay:3000});
												return;
											}
										}
										if(!$("#query_type").val()){
											return false;
										} else {
											App.blockUI($(".histtory_query_chart_div"));//开始loading
											var params = {};
											params.packCode = $("#query_pack_code").val();
											params.startTime = $("#query_startTime").val();
											params.endTime = $("#query_endTime").val();
											params.option = $("#query_type").val();
											util.ajaxDownload("monitor/historyQuery/export.mvc", params, ".histtory_query_chart_div");
					                }
					               }
					            },
					            dataZoom: {
					                yAxisIndex: 'none'
					            },
					            restore: {},
					            saveAsImage: {}
					        }
					    },
					    dataZoom : {
					        show : true,
					        realtime : true,
					        start : 0,
					        end : 100
					    },
					    xAxis:  {
					        type: 'category',
					        name:'时间',
					        splitLine:{show:true},
					        nameTextStyle:{
					        	color:'#89CBFD'
					        },
					        boundaryGap: false,
					        data: dataX
					    },
					    yAxis: [{
					        type: 'value',
					        position:'left',
					        splitLine:{show:true},
					        name:yaxisName,
					        nameTextStyle:{
					        	color:'#89CBFD'
					        },
					        axisLabel: {
					            formatter: '{value}'+unit
					        }
					    },
					    {
					        type: 'value',
					        position:'right',
					        name:yaxisName2,
					        nameTextStyle:{
					        	color:'#89CBFD'
					        },
					        axisLabel: {
					            formatter: '{value}'+unit
					        }
					    }],
					    series: series
					};
			    var myChart = echarts.init(document.getElementById(chart_div_id));
			    myChart.setOption(option,true);
			    App.unblockUI($("#histtory_query_chart_div"));//停止loading
		},
		
		/**
		 * 进入页面加载空表格
		 */
		setDefaultChart:function(){
			var series = [
					        {
					            name:'soc',
					            type:'line',
					            data:[],
					            markPoint: {
					                data: [
					                    {type: 'max', name: '最大值'},
					                    {type: 'min', name: '最小值'}
					                ]
					            }
					        }
					    ]
		   history_query.chart_config("SOC曲线图",['SOC'], [], '%', series, "histtory_query_chart_div", 'SOC');
		}
		
	}
}();
